import {inject, provide, reactive, toRaw} from "plain-design-composition";
import {MicroApp, Page} from "plain-micro-application";
import {MicroNavigationPageSingleCase} from "@/micro/nav/components/MicroNavigationPageSingleCase";

const PROVIDE_KEY = '@@useSingleApplicationRender'


interface iRequestHandler {
    showPage: (page: Page) => () => void,
}

interface iRequestItemInfo {
    app: MicroApp,
    curPage: Page | null,
    handler: iRequestHandler,
}

interface iRequestSingleApplicationPage {
    requestSingleApplicationPage: (app: MicroApp) => iRequestHandler
}

export function useSingleApplicationRender() {

    const state = reactive({
        list: [] as iRequestItemInfo[]
    })

    const requestSingleApplicationPage = (app: MicroApp) => {
        let findItem = (state.list as iRequestItemInfo[]).find(item => item.app == app || toRaw(item.app) == app)
        if (!findItem) {
            findItem = {
                app,
                curPage: null,
                handler: {
                    showPage: (page: Page) => {
                        findItem!.curPage = page
                        page = findItem!.curPage
                        return () => {
                            if (!!findItem!.curPage && (findItem!.curPage == page)) {
                                findItem!.curPage = null
                            }
                        }
                    },
                },
            }
            state.list.push(findItem)
            findItem = state.list[state.list.length - 1] as any
        }
        return findItem!.handler
    }

    provide(PROVIDE_KEY, {requestSingleApplicationPage})

    const renderSingleCasePage = () => {
        return state.list.map(({app, curPage}, index) => (
            <MicroNavigationPageSingleCase key={`single-case-${index}`} app={app as any} page={curPage}/>
        ))
    }

    return {
        renderSingleCasePage,
    }
}

export function injectRequestSingleApplicationPage() {
    return inject<iRequestSingleApplicationPage>(PROVIDE_KEY)
}